﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.IO;
using System.Threading;



namespace PhoneApp6
{
    public class cl
    {
        bool isNeedCache;
        public delegate void LoadDataCompleted(System.Collections.ObjectModel.ObservableCollection<dls> dtc);
        public delegate void LoadDataCompleted1(System.Collections.ObjectModel.ObservableCollection<dls> dtc);
        public LoadDataCompleted OnLoadDataCompleted;
        public LoadDataCompleted1 OnLoadDataCompleted1;

        private IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
        string fileName = "1.txt";
        public void savetolocal(System.Collections.ObjectModel.ObservableCollection<dls> myd)
        {
            using (IsolatedStorageFileStream stream = storage.CreateFile(fileName))
            {
                //  serializer.Serialize(stream, myd);
                DataContractSerializer xc = new DataContractSerializer(typeof(System.Collections.ObjectModel.ObservableCollection<dls>));
                xc.WriteObject(stream, myd);


            }
        }
        public void frmlocal()
        {
           System.Collections.ObjectModel.ObservableCollection<dls> myd1 = new System.Collections.ObjectModel.ObservableCollection<dls>();
            using (IsolatedStorageFileStream stream1 = storage.OpenFile(fileName, System.IO.FileMode.Open))
            {
                DataContractSerializer xc1 = new DataContractSerializer(typeof(System.Collections.ObjectModel.ObservableCollection<dls>));
                myd1 = (System.Collections.ObjectModel.ObservableCollection<dls>)xc1.ReadObject(stream1);
                //this.OnLoadDataCompleted(myd1);
               // System.Collections.ObjectModel.ObservableCollection<dls> dtc = myd1;
                stream1.Close();

                this.OnLoadDataCompleted1(myd1);
              

            }
            
           

        }
       
        public System.Collections.ObjectModel.ObservableCollection<dls> frmlocal1()
        {
            System.Collections.ObjectModel.ObservableCollection<dls> myd;
            using (IsolatedStorageFileStream stream = storage.OpenFile(fileName, System.IO.FileMode.Open))
            {
                DataContractSerializer xc = new DataContractSerializer(typeof(System.Collections.ObjectModel.ObservableCollection<dls>));
                myd = (System.Collections.ObjectModel.ObservableCollection<dls>)xc.ReadObject(stream);

                return myd;

            }

        }
        public void frmnet(bool isNeedCache)
        {

            this.isNeedCache = isNeedCache;
            string sid = IsolatedStorageSettings.ApplicationSettings["sessionid"].ToString();
            CookieContainer cc = App.cc;
            String pspt = "http://lixian.xunlei.com";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pspt);
            req.Method = "get";
            req.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, */*";
            //req.Referer = "http://cloud.vip.xunlei.com/task.html";
            req.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
            // req.Host = "jump.xunlei.com";
            // req.KeepAlive = true;

            req.CookieContainer = cc;
            //  HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            req.BeginGetResponse(r =>
            {
                // HttpWebResponse resp = null;
                HttpWebRequest httpRequest = (HttpWebRequest)r.AsyncState;
                HttpWebResponse resp = (HttpWebResponse)httpRequest.EndGetResponse(r);
                using (var reader = new StreamReader(resp.GetResponseStream()))
                {
                    string stroe = reader.ReadToEnd();
                    reader.Close();
                    Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        //  textBox1.Text = stroe;
                    }));
                }
                cc.Add(resp.ResponseUri, resp.Cookies);
                DateTime dt = DateTime.Now;

                string tm = dt.DayOfWeek.ToString().Substring(0, 3);
                string ms = dt.ToLongTimeString();
                string dyo = "";
                int dy = dt.Day;
                string yr = dt.Year.ToString();
                
                    dyo = string.Format("0{0}", dy.ToString());
                
                string m = null;
                switch (dt.Month.ToString())
                {
                    case "1": m = "Jan"; break;
                    case "2": m = "Feb"; break;
                    case "3": m = "Mar"; break;
                    case "4": m = "Apr"; break;
                    case "5": m = "May"; break;
                    case "6": m = "Jun"; break;
                    case "7": m = "Jul"; break;
                    case "8": m = "Aug"; break;
                    case "9": m = "Sep"; break;
                    case "0": m = "Oct"; break;
                    case "11": m = "Nov"; break;
                    case "12": m = "Dec"; break;

                }
                string timeout = string.Format("{0}%20{1}%2{2}%20{3}%20UTC+0800%20{4}", tm, m, dyo, ms, yr);
                String FormURL =  string.Format("http://dynamic.cloud.vip.xunlei.com/interface/showtask_unfresh?callback=jsonp1369797739781&t={0}&type_id=4&page=1&tasknum=100&p=1&interfrom=task",timeout);
                // String FormURL = "http://dynamic.cloud.vip.xunlei.com/interface/showtask_unfresh?callback=jsonp1369797739781&t=Wed May 29 11:22:20 UTC+0800 2013&type_id=4&page=1&tasknum=30&p=1&interfrom=task";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FormURL);
                request.Method = "GET";
                // request.Referer = "http://dynamic.cloud.vip.xunlei.com/user_task?userid=22403143&st=4";
                // request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
                // request.Host = "dynamic.cloud.vip.xunlei.com";
                //request.KeepAlive = true;
                request.CookieContainer = cc;
                request.BeginGetResponse(r1 =>
                {
                    // HttpWebResponse resp = null;
                    HttpWebRequest httpRequest1 = (HttpWebRequest)r1.AsyncState;
                    HttpWebResponse respuest = (HttpWebResponse)httpRequest1.EndGetResponse(r1);
                    using (var reader = new StreamReader(respuest.GetResponseStream()))
                    {
                        string org = reader.ReadToEnd();
                        reader.Close();
                        Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            List<string> slipt1 = new List<string>();
                            List<string> sllxut = new List<string>();
                            List<string> slurlut = new List<string>();
                            string http = "http://";
                            //string ts = string.Format("taskname");
                            while (org.Length > 3000)
                            {
                                string ipt1 = org.Substring(org.IndexOf("taskname") + 11, org.IndexOf(",", org.IndexOf("taskname")) - org.IndexOf("taskname") - 12);
                                slipt1.Add(ipt1);
                                if (org.IndexOf(",", org.IndexOf("lixian_url")) - org.IndexOf("lixian_url") > 22)
                                {
                                    string lxurl = org.Substring(org.IndexOf("lixian_url") + 22, org.IndexOf(",", org.IndexOf("lixian_url")) - org.IndexOf("lixian_url") - 23);

                                    string lxut = http + lxurl;
                                    lxut = lxut.Replace(@"\", "");
                                    sllxut.Add(lxut);
                                }
                                else
                                {
                                    sllxut.Add("nolixian");
                                }
                                // richTextBox1.AppendText(ipt1);
                                org = org.Substring(org.IndexOf("lixian_url") + 19, org.LastIndexOf(")") - org.IndexOf("lixian_url") - 18);
                                //richTextBox1.AppendText(org);
                                if (org.IndexOf("http:") > 1)
                                {
                                    string url = org.Substring(org.IndexOf("http:") + 9, org.IndexOf(",", org.IndexOf("http:")) - org.IndexOf("http:") - 10);
                                    string urlut = http + url;
                                    urlut = urlut.Replace(@"\", "");
                                    slurlut.Add(urlut);
                                }
                                // richTextBox1.AppendText(url);
                                org = org.Substring(org.IndexOf("taskname_show") + 13);
                                // richTextBox1.AppendText(org);
                            }
                            System.Collections.ObjectModel.ObservableCollection<dls> dtc = new System.Collections.ObjectModel.ObservableCollection<dls>();
                            for (int i = 0; i < slurlut.Count-1; i++)
                            {
                                dls myd = new dls();
                                {
                                    myd.no = i+1;
                                    myd.dln = slipt1[i];
                                    myd.dlx = sllxut[i];
                                    myd.dlu = slurlut[i];
                                }
                                dtc.Add(myd);

                            }
                            if (isNeedCache)
                            {
                                savetolocal(dtc);
                            }
                            this.OnLoadDataCompleted(dtc);

                        }));

                    }
                    //  cc.Add(respuest.ResponseUri, respuest.Cookies);
                }, request);

            }, req);


            //richTextBox1.AppendText(org);




        }
        public void seach()
        {
            if (storage.FileExists(fileName))
            {
                frmlocal();
            }
            else
            {
                frmnet(true);

            }
        }
        private void readlocal(object sender, EventArgs e)
        {
            //this.lst.DataContext = frmlocal().Reverse().ToList();
        }

        private void refh(object sender, EventArgs e)
        {
            frmnet(true);
        }
        public void addtsk(string orgc)
        {
            App.mt.WaitOne(1000);
           
                string userid = App.userid;
                string sid = IsolatedStorageSettings.ApplicationSettings["sessionid"].ToString();
                CookieContainer cc = App.cc;
                String pspt = "http://lixian.xunlei.com";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pspt);
                req.Method = "get";
                req.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, */*";
                //req.Referer = "http://cloud.vip.xunlei.com/task.html";
                req.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
                // req.Host = "jump.xunlei.com";
                // req.KeepAlive = true;

                req.CookieContainer = cc;
                //  HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                req.BeginGetResponse(r =>
                {
                    // HttpWebResponse resp = null;
                    HttpWebRequest httpRequest = (HttpWebRequest)r.AsyncState;
                    HttpWebResponse resp = (HttpWebResponse)httpRequest.EndGetResponse(r);
                    using (var reader = new StreamReader(resp.GetResponseStream()))
                    {
                        string stroe = reader.ReadToEnd();
                        reader.Close();
                        Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            //  textBox1.Text = stroe;
                        }));
                    }

                    cc.Add(resp.ResponseUri, resp.Cookies);
                    CookieCollection ck = resp.Cookies;
                    foreach (Cookie co in ck)
                    {
                        // richTextBox1.AppendText(co.Name);
                        if (co.Name == "userid")
                        {
                            //  richTextBox1.AppendText(co.Value);
                            userid = co.Value.ToString();
                        }
                    }
                    String FormURL = string.Format("http://dynamic.cloud.vip.xunlei.com/interface/task_check?callback=queryCid&url={0}&interfrom=task&random=137057249790266759.97150089616&tcache=1370572501619 ", HttpUtility.UrlEncode(orgc));
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FormURL);
                    request.Method = "GET";
                    //  request.Referer = "http://dynamic.cloud.vip.xunlei.com/user_task?userid=22403143&st=4";
                    //  request.ContentType = "application/x-www-form-urlencoded";
                    request.Accept = "text/html, application/xhtml+xml, */*";
                    request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
                    //    request.Host = "dynamic.cloud.vip.xunlei.com";
                    //   request.KeepAlive = true;
                    request.CookieContainer = cc;
                    request.BeginGetResponse(r1 =>
                    {
                        // HttpWebResponse resp = null;
                        HttpWebRequest httpRequest1 = (HttpWebRequest)r1.AsyncState;
                        HttpWebResponse respuest = (HttpWebResponse)httpRequest1.EndGetResponse(r1);
                        using (var reader = new StreamReader(respuest.GetResponseStream()))
                        {
                            string org = reader.ReadToEnd();
                            reader.Close();
                            Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
                            {
                                string qeri = org;
                                string cid = qeri.Substring(qeri.IndexOf("'") + 1, qeri.IndexOf(",", qeri.IndexOf("'")) - qeri.IndexOf("'") - 2);
                                qeri = qeri.Substring(qeri.IndexOf(",") + 1);
                                string gcid = qeri.Substring(qeri.IndexOf("'") + 1, qeri.IndexOf(",", qeri.IndexOf("'")) - qeri.IndexOf("'") - 2);
                                qeri = qeri.Substring(qeri.IndexOf(",") + 1);
                                string size1 = qeri.Substring(qeri.IndexOf("'") + 1, qeri.IndexOf(",", qeri.IndexOf("'")) - qeri.IndexOf("'") - 2);
                                qeri = qeri.Substring(qeri.IndexOf(",") + 1);
                                qeri = qeri.Substring(qeri.IndexOf(",") + 1);
                                string filenamet = qeri.Substring(qeri.IndexOf("'") + 1, qeri.IndexOf(",", qeri.IndexOf("'")) - qeri.IndexOf("'") - 2);
                                DateTime dt = DateTime.Now;

                                string tm = dt.DayOfWeek.ToString().Substring(0, 3);
                                string ms = dt.ToLongTimeString();
                                string dyo = "";
                                int dy = dt.Day;
                                string yr = dt.Year.ToString();

                                dyo = string.Format("0{0}", dy.ToString());

                                string m = null;
                                switch (dt.Month.ToString())
                                {
                                    case "1": m = "Jan"; break;
                                    case "2": m = "Feb"; break;
                                    case "3": m = "Mar"; break;
                                    case "4": m = "Apr"; break;
                                    case "5": m = "May"; break;
                                    case "6": m = "Jun"; break;
                                    case "7": m = "Jul"; break;
                                    case "8": m = "Aug"; break;
                                    case "9": m = "Sep"; break;
                                    case "0": m = "Oct"; break;
                                    case "11": m = "Nov"; break;
                                    case "12": m = "Dec"; break;

                                }
                                string timeout = string.Format("{0}%20{1}%2{2}%20{3}%20UTC+0800%20{4}", tm, m, dyo, ms, yr);
                                string work = string.Format("http://dynamic.cloud.vip.xunlei.com/interface/task_commit?callback=ret_task&uid={0}&cid={1}&gcid={2}&size={3}&goldbean=0&silverbean=0&t={4}&url={5}&type=0&o_page=history&o_taskid=0&class_id=0&database=undefined&interfrom=task&time={6}&noCacheIE=1370574671359 ", userid, cid, gcid, size1, filenamet, HttpUtility.UrlEncode(orgc), timeout);
                                // richTextBox1.AppendText(work);
                                HttpWebRequest reqw = (HttpWebRequest)WebRequest.Create(work);
                                reqw.Method = "GET";
                                reqw.Accept = "text/html, application/xhtml+xml, */*";

                                //  reqw.Referer = "http://cloud.vip.xunlei.com/task.html?error=1";
                                reqw.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
                                //  reqw.Host = "dynamic.cloud.vip.xunlei.com";
                                //  reqw.KeepAlive = true;
                                reqw.CookieContainer = cc;
                                reqw.BeginGetResponse(r12 =>
                    {
                        // HttpWebResponse resp = null;
                        HttpWebRequest httpRequest12 = (HttpWebRequest)r12.AsyncState;
                        HttpWebResponse respuest12 = (HttpWebResponse)httpRequest12.EndGetResponse(r12);
                        frmnet(true);

                    }, reqw);
                            }));

                        }
                        //  cc.Add(respuest.ResponseUri, respuest.Cookies);
                    }, request);
                }, req);
                
            
        }
    }


}
